package com.leesche.zcsp.node.web.controller.web.v2.account;

import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.controller.web.v2.admin.WebAdminController;
import com.leesche.zcsp.node.web.service.PubDevGiftStockService;
import com.leesche.zcsp.node.web.service.PubDevicePayDetailStatisticsService;
import com.leesche.zcsp.node.web.service.impl.data.read.PubDevicePayDetailStatisticsDto;
import com.leesche.zcsp.node.web.service.impl.data.read.QueryPubDevGiftStockCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.QueryPubDevicePayDetailStatisticsCondition;
import com.leesche.zcsp.node.web.vo.v2.AccountSummaryVo;
import com.leesche.zcsp.node.web.vo.v2.enums.AccountEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.leesche.zcsp.node.utils.UtilDate.*;

/**
 * Created by kaider on 2017/1/3.
 *
 */
@Controller
@RequestMapping("/v2/factory/account")
public class WebFactoryAccountController extends WebAdminController {

    private final static Logger LOGGER = LoggerFactory.getLogger(WebFactoryAccountController.class);

    private static final String SHOW_VIEW = "web/v2/account/factory/showView";

    @Autowired
    private PubDevicePayDetailStatisticsService statisticsService;
    @Autowired
    private PubDevGiftStockService giftStockService;

    /**
     *
     * @param showView
     * @param giftStockCondition
     * @param statisticsCondition
     * @param model
     * @return
     */
    @RequestMapping(value = "/{showView}", method = RequestMethod.GET)
    public String showView(
            @PathVariable("showView") String showView,
            QueryPubDevGiftStockCondition giftStockCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition,
            Model model
    ) {
        Long adminId = getFactoryAdminId();
        giftStockCondition.setAdminId(adminId);
        statisticsCondition.setUserId(adminId);
        getQueryTime(showView,model,statisticsCondition);
        getBarOption(model,giftStockCondition,statisticsCondition);
        getLineOption(showView,model,statisticsCondition);
        getStackBarOption(showView,model,statisticsCondition);
        model.addAttribute("view", "1");
        return SHOW_VIEW;
    }

    /**
     * 账目时间查询
     * @param giftStockCondition
     * @param statisticsCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Map<String,Object> search(
            QueryPubDevGiftStockCondition giftStockCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition
    ) {
        AccountSummaryVo vo;
        List<String> dayVal = new ArrayList<String>();
        List<String> dataVal = new ArrayList<String>();
        List<String> weChatVal = new ArrayList<String>();
        List<String> aliPayVal = new ArrayList<String>();
        List<String> sumPayVal = new ArrayList<String>();
        try {
            Long adminId = getFactoryAdminId();
            giftStockCondition.setAdminId(adminId);
            statisticsCondition.setUserId(adminId);
            dayVal = getDayVal(0,1,statisticsCondition);
            dataVal = getDataVal(0,statisticsCondition,1);
            weChatVal = getDataVal(0,statisticsCondition,2);
            aliPayVal = getDataVal(0,statisticsCondition,3);
            sumPayVal = getDataVal(0,statisticsCondition,4);
            vo = searchParam(giftStockCondition,statisticsCondition);
            if(statisticsCondition.getStime().equals("") && statisticsCondition.getEtime().equals("")){
                String sDate = getSimpleDate();
                String sWeek = getWeek(sDate);
                vo.setCreateDate(sDate+"  ~  "+sWeek);
            }
            return WebResult.success()
                    .put("AccountSummary", vo)
                    .put("dayVal",dayVal)
                    .put("dataVal",dataVal)
                    .put("weChatVal",weChatVal)
                    .put("aliPayVal",aliPayVal)
                    .put("sumPayVal",sumPayVal)
                    .toMap();
        } catch (NumberFormatException e) {
            LOGGER.error(e.getMessage(),e);
            vo = new AccountSummaryVo();
            vo.toZero();
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 堆行图查询
     * @param flag
     * @param giftStockCondition
     * @param statisticsCondition
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/search/{flag}", method = RequestMethod.POST)
    public Map<String,Object> search(
            @PathVariable("flag") Integer flag,
            QueryPubDevGiftStockCondition giftStockCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition,
            Model model
    ) {
        AccountSummaryVo vo;
        List<String> dayVal = new ArrayList<String>();
        List<String> weChatVal = new ArrayList<String>();
        List<String> aliPayVal = new ArrayList<String>();
        List<String> sumPayVal = new ArrayList<String>();
        Long adminId = getFactoryAdminId();
        giftStockCondition.setAdminId(adminId);
        statisticsCondition.setUserId(adminId);
        String showView = AccountEnum.parse(flag).getMessage();
        getQueryTime(showView,model,statisticsCondition);
        try {
            if(statisticsCondition.getsDate()!=null){
                dayVal = getDayVal(flag,0,statisticsCondition);
                weChatVal = getDataVal(flag,statisticsCondition,2);
                aliPayVal = getDataVal(flag,statisticsCondition,3);
                sumPayVal = getDataVal(flag,statisticsCondition,4);
            }else{
                dayVal = getDayVal(flag,0,statisticsCondition);
                weChatVal = getDataVal(flag,statisticsCondition,2);
                aliPayVal = getDataVal(flag,statisticsCondition,3);
                sumPayVal = getDataVal(flag,statisticsCondition,4);
            }
            return WebResult.success()
                    .put("dayVal",dayVal)
                    .put("weChatVal",weChatVal)
                    .put("aliPayVal",aliPayVal)
                    .put("sumPayVal",sumPayVal)
                    .toMap();
        } catch (NumberFormatException e) {
            LOGGER.error(e.getMessage(),e);
            vo = new AccountSummaryVo();
            vo.toZero();
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设置周期获取的时间查询条件
     * @param showView
     * @param model
     * @param statisticsCondition
     * @return
     */
    private Model getQueryTime(
            String showView,
            Model model,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition
    ) {
        String sDate = getSimpleDate();
        String sTime = "";
        String eTime = "";
        AccountEnum accountEnum = AccountEnum.parse(showView);
        switch (accountEnum.getCode()) {
            case 1:
                statisticsCondition.setsDate(sDate);
                sTime = sDate;
                eTime = getWeek(sDate);
                break;
            case 2:
                sTime = getCurrentMonday(sDate, 0);
                eTime = getPreviousSunday(sDate, 0);
                statisticsCondition.setStime(sTime);
                statisticsCondition.setEtime(eTime);
                break;
            case 3:
                sTime = getMinMonthDate(sDate, 0);
                eTime = getMaxMonthDate(sDate, 0);
                statisticsCondition.setStime(sTime);
                statisticsCondition.setEtime(eTime);
                break;
            default:
                break;
        }
        model.addAttribute("cur", accountEnum.getCode());
        model.addAttribute("stime", sTime);
        model.addAttribute("etime", eTime);
        return model;
    }

    /**
     * 获取账目信息/获取柱状图/获取饼状图
     * @param model
     * @param giftStockCondition
     * @param statisticsCondition
     * @return
     */
    private Model getBarOption(
            Model model,
            QueryPubDevGiftStockCondition giftStockCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition
    ) {
        AccountSummaryVo vo;
        try {
            vo = searchParam(giftStockCondition,statisticsCondition);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage(),e);
            vo = new AccountSummaryVo();
            vo.toZero();
        }
        model.addAttribute("AccountSummary", vo);
        return model;
    }

    /**
     * 条件查询返回数据
     * @param giftStockCondition
     * @param statisticsCondition
     * @return
     * @throws NumberFormatException
     */
    private AccountSummaryVo searchParam(
            QueryPubDevGiftStockCondition giftStockCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition
    ) throws NumberFormatException {
        AccountSummaryVo vo = new AccountSummaryVo();
        if(statisticsCondition.getsDate()!=null&&
            statisticsCondition.getStime()!=null&&
            statisticsCondition.getEtime()!=null&&
            !statisticsCondition.getStime().equals("")&&
            !statisticsCondition.getEtime().equals("")
        ){
            statisticsCondition.setsDate("");
        }
        PubDevicePayDetailStatisticsDto statisticsDto = statisticsService.findFactoryByCondition(statisticsCondition);
        Integer giftCount = giftStockService.getFactoryGiftCount(giftStockCondition);
        vo.setCreateDate(statisticsCondition.getStime()+"  ~  "+statisticsCondition.getEtime());
        if (statisticsDto != null) {
            statisticsDto.setGiftCount(giftCount!=null?giftCount:0);
            //现金数量
            vo.inventoryCashQuantity(
                    statisticsDto.getOnebalance(),
                    statisticsDto.getFivebalance(),
                    statisticsDto.getTenbalance(),
                    statisticsDto.getTwentybalance(),
                    statisticsDto.getFiftybalance(),
                    statisticsDto.getHundredbalance());

            //统计收益
            vo.inventoryIncome(statisticsDto.getBillmoney(),
                    statisticsDto.getCoinmoney(),
                    statisticsDto.getWechatmoney(),
                    statisticsDto.getAlipaymoney());

            //统计非费用收益
            vo.inventoryNotIncome(
                    statisticsDto.getIntdata1(),
                    statisticsDto.getGamecoinbalnce(),
                    statisticsDto.getGiftbalance(),
                    statisticsDto.getCoinbalance(),
                    statisticsDto.getGiftCount());

        }else{
            vo.toZero();
        }
        return vo;
    }

    /**
     * 获取折线图
     * @param showView
     * @param model
     * @param statisticsCondition
     * @return
     */
    private Model getLineOption(
            String showView,
            Model model,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition
    ) {
        List<String> dayVal = new ArrayList<String>();
        List<String> dataVal = new ArrayList<String>();
        Integer flag = AccountEnum.parse(showView).getCode();
        if(statisticsCondition.getsDate()!=null){
            dayVal = getDayVal(flag,1,statisticsCondition);
            dataVal = getDataVal(flag,statisticsCondition,1);
        }else{
            dayVal = getDayVal(flag,1,statisticsCondition);
            dataVal = getDataVal(flag,statisticsCondition,1);
        }
        model.addAttribute("dayVal",dayVal);
        model.addAttribute("dataVal",dataVal);
        return model;
    }

    /**
     * 获取堆叠图
     * @param showView
     * @param model
     * @param statisticsCondition
     * @return
     */
    private Model getStackBarOption(
            String showView,
            Model model,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition
    ) {
        List<String> dayVal = new ArrayList<String>();
        List<String> weChatVal = new ArrayList<String>();
        List<String> aliPayVal = new ArrayList<String>();
        List<String> sumPayVal = new ArrayList<String>();
        Integer flag = AccountEnum.parse(showView).getCode();
        if(statisticsCondition.getsDate()!=null){
            dayVal = getDayVal(flag,1,statisticsCondition);
            weChatVal = getDataVal(flag,statisticsCondition,2);
            aliPayVal = getDataVal(flag,statisticsCondition,3);
            sumPayVal = getDataVal(flag,statisticsCondition,4);
        }else{
            dayVal = getDayVal(flag,1,statisticsCondition);
            weChatVal = getDataVal(flag,statisticsCondition,2);
            aliPayVal = getDataVal(flag,statisticsCondition,3);
            sumPayVal = getDataVal(flag,statisticsCondition,4);
        }
        model.addAttribute("dayStackVal",dayVal);
        model.addAttribute("weChatVal",weChatVal);
        model.addAttribute("aliPayVal",aliPayVal);
        model.addAttribute("sumPayVal",sumPayVal);
        return model;
    }

    /**
     * 获取往前的天数数组
     * @param flag
     * @param showType 显示类型 1：默认显示，0：查询显示
     * @param statisticsCondition
     * @return
     */
    private List<String> getDayVal(
            Integer flag,
            Integer showType,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition
    ) {
        String sDate = statisticsCondition.getsDate();
        String sTime = statisticsCondition.getStime();
        String eTime = statisticsCondition.getEtime();
        List<String> dayVal = new ArrayList<String>();
        if(flag==1){
            for(int i=6;i>-1;i--){
                String day = getBeforeDay(1,i,sDate);
                if(showType==1){
                    dayVal.add("'"+day+"'");
                }else{
                    dayVal.add(day);
                }
            }
        }else if(flag==2){
            for(int i=6;i>-1;i--){
                String monday = getBeforeWeekDate(1,i,sTime);
                String sunday = getBeforeWeekDate(1,i,eTime);
                if(showType==1){
                    dayVal.add("'"+monday+"~"+sunday+"'");
                }else{
                    dayVal.add(monday+"~"+sunday);
                }
            }
        }else if(flag==3){
            for(int i=6;i>-1;i--){
                String begin = getBeforeMonthDate(1,1,i,sTime);
                String end = getBeforeMonthDate(1,0,i,eTime);
                if(showType==1){
                    dayVal.add("'"+begin+"~"+end+"'");
                }else{
                    dayVal.add(begin+"~"+end);
                }
            }
        }else{
            int num=6;
            if(!sTime.equals("")||!eTime.equals("")){
                num = (int)getTimeDifference(eTime,sTime);
            }else{
                eTime = getSimpleDate();
            }
            for(int i=num;i>-1;i--){
                String day = getBeforeDay(1,i,eTime);
                dayVal.add(day);
            }
        }
        return dayVal;
    }

    /**
     * 获取设备总账
     * @param flag showView的值(AccountEnum)
     * @param statisticsCondition
     * @param accountType 账目类型 1:总账，2：微信，3：支付宝，4：线上支付
     * @return
     */
    private List<String> getDataVal(
            int flag,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition,
            int accountType
    ) {
        List<String> dataVal = new ArrayList<String>();
        String sDateTemp = statisticsCondition.getsDate();
        String sTimeTemp = statisticsCondition.getStime();
        String eTimeTemp = statisticsCondition.getEtime();
        if(flag==1){
            for(int i=6;i>-1;i--){
                String sDate = getBeforeDay(0,i,sDateTemp);
                statisticsCondition.setsDate(sDate);
                String sumAccount = getDeviceSumAccount(statisticsCondition,accountType);
                dataVal.add(sumAccount);
            }
        }else if(flag==2){
            for(int i=6;i>-1;i--){
                String monday = getBeforeWeekDate(0,i,sTimeTemp);
                String sunday = getBeforeWeekDate(0,i,eTimeTemp);
                statisticsCondition.setStime(monday);
                statisticsCondition.setEtime(sunday);
                String sumAccount = getDeviceSumAccount(statisticsCondition,accountType);
                dataVal.add(sumAccount);
            }
        }else if(flag==3){
            for(int i=6;i>-1;i--){
                String begin = getBeforeMonthDate(0,1,i,sTimeTemp);
                String end = getBeforeMonthDate(0,0,i,eTimeTemp);
                statisticsCondition.setStime(begin);
                statisticsCondition.setEtime(end);
                String sumAccount = getDeviceSumAccount(statisticsCondition,accountType);
                dataVal.add(sumAccount);
            }
        }else{
            if(!sTimeTemp.equals("")||!eTimeTemp.equals("")) {
                int num = (int) getTimeDifference(eTimeTemp, sTimeTemp);
                for(int i=num;i>-1;i--){
                    String sDate = getBeforeDay(0,i,eTimeTemp);
                    statisticsCondition.setsDate(sDate);
                    String sumAccount = getDeviceSumAccount(statisticsCondition,accountType);
                    dataVal.add(sumAccount);
                }
            }else {
                eTimeTemp = getSimpleDate();
                for(int i=6;i>-1;i--){
                    String sDate = getBeforeDay(0,i,eTimeTemp);
                    statisticsCondition.setsDate(sDate);
                    String sumAccount = getDeviceSumAccount(statisticsCondition,accountType);
                    dataVal.add(sumAccount);
                }
            }
        }
        return dataVal;
    }

    /**
     * 获取设备账目总值
     * @param statisticsCondition
     * @param flag 1:总账，2：微信，3：支付宝，4：线上支付
     * @return
     */
    private String getDeviceSumAccount(
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition,
            int flag
    ) {
        DecimalFormat df = new DecimalFormat(".00");
        String sumAccount="0.00";
        PubDevicePayDetailStatisticsDto statisticsDto = statisticsService.findFactoryByCondition(statisticsCondition);
        if(statisticsDto!=null){
            switch (flag){
                //总账
                case 1:
                    sumAccount = statisticsDto.getLedger();
                    break;
                //微信
                case 2:
                    sumAccount = statisticsDto.getWechatmoney()/100+"";
                    break;
                //支付宝
                case 3:
                    sumAccount = statisticsDto.getAlipaymoney()/100+"";
                    break;
                //线上支付
                case 4:
                    sumAccount = (statisticsDto.getWechatmoney()+ statisticsDto.getAlipaymoney())/100+"";
                    break;
                default:
                    break;
            }
            Double temp = Double.parseDouble(sumAccount);
            sumAccount = df.format(temp);
        }
        return sumAccount;
    }

}
